<?php

namespace app\admin\controller\finance\extract;

use app\common\controller\Backend;
use app\admin\model\AuthDepartment;
use fast\Tree;
use PHPExcel_IOFactory;
/**
 * 财务提成_周管理
 *
 * @icon fa fa-circle-o
 */
class Week extends Backend
{
    protected $searchFields = 'id,name,start_time,end_time';
    protected $noNeedLogin = ['type_info'];
    /**
     * Week模型对象
     * @var \app\admin\model\finance\extract\Week
     */
    protected $model = null;

    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\admin\model\finance\extract\Week;
		$dept = GetBaseInfo('Dept');
		$groupList = collection(AuthDepartment::field('*,parentid as pid')->where('id','in',''.implode(',',$dept).'')->select())->toArray();
        Tree::instance()->init($groupList);
		//权限
		$this->RoleFinance = GetRoleFinance();
        $groupdata = [];
		$result = [];
		if(!empty($this->RoleFinance['role'])){
			$groups = $this->auth->getGroups();
			$userid = \think\Session::get('admin')['userid'];
			$temp = [];
			foreach (explode(',',$this->RoleFinance['role']) as $m => $n){
				$childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(2));
				if($n == 2){
					foreach ($childlist as $k => $v){
                       $temp[$v['id']] = $v['name'];
					}
				}else{
					foreach ($childlist as $k => $v){	
                       if($v['id'] == $n || $v['parentid'] == $n) $temp[$v['id']] = $v['name'];
					}
				}
			}
			$groupdata = $temp;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->view->assign("statusList", $this->model->getStatusList());
        $start_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['start_time'];
		$end_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['end_time'];
		$this->view->assign("DefaultsTime", $start_time.','.$end_time);
		$this->view->assign("DefaultsDate", date('Y'));
		$this->view->assign("DefaultsDateM", date('m'));
		$this->view->assign("divisionMethodList", $this->model->getDivisionMethodList());
		$this->view->assign("divisionMethodRoundList", $this->model->getDivisionMethodRoundList());
		$this->view->assign("Generate_Week", \think\Config::get('finance.Generate_Week'));
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index(){
		
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()){
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')){
                return $this->selectpage();
            }
			$fi_where = $this->RoleFinance['where'];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->where($fi_where)
                    ->order($sort, $order)
					->group('start_time')
                    ->count();
            $list = $this->model
                    ->where($where)
                    ->where($fi_where)
                    ->order($sort, $order)
					->group('start_time')
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->visible(['id','name','start_time','end_time','division_method','division_method_round','status','department_text','status_desc','createtime','updatetime']);
            }
			//print_r($this->model->getLastSql());die;
            $list = collection($list)->toArray();
				//print_R($list);die;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看
     */
    public function index2(){
		
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')){
                return $this->selectpage();
            }
			$fi_where = $this->RoleFinance['where'];
			
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			//print_R($where);die;
            $total = $this->model
                    ->where($where)
                    ->where($fi_where)
                    ->order($sort, $order)
                    ->count();
		//	print_R($this->model->getLastSql());die;
            $list = $this->model
                    ->where($where)
                    ->where($fi_where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->visible(['id','name','start_time','end_time','division_method','division_method_round','status','department_text','status_desc','createtime','updatetime']);
                
            }
			//print_r($this->model->getLastSql());die;
            $list = collection($list)->toArray();
				//print_R($list);die;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
     /*
     * 周次分组
     *
    */
    public function group($start_time = NULL , $end_time = NULL){
        if($start_time && $end_time){

             $row = [];
             $row['start_time'] = $start_time;
             $row['end_time'] = $end_time;
             $row['name'] = date('m.d',strtotime($row['start_time'])).'-'.date('m.d',strtotime($row['end_time'])).'周数据';
             $row['year'] = date('Y',strtotime($row['start_time']));
             $row['month'] = date('m',strtotime($row['start_time']));
             $row['publish'] = \think\Session::get('admin')['userid'];
             $row['z_publish'] = \think\Session::get('admin')['userid'];
        }else{
            $row = GenerateWeek(2);
        }
        if ($this->request->isPost() && $this->request->isAjax()) {
            $post = $this->request->post("data/a");
            $array = array();
            foreach ($post as $k => $v) {
                if ($this->thecks($v)) {
                    $array[$k] = $v;
                }
            }
            if (is_array($array) && $array && $row){
                $check = GenerateGroup($array,$row);
                $data['starttime']=$row['start_time'];
                $data['endtime']=$row['end_time'];
                $data['data'] = serialize($array);
                if ($inteInfo = \think\Db::name("integral_group")->field('id')->where(array('starttime'=>$row['start_time'],'endtime'=>$row['end_time']))->find()){
                    $id = $inteInfo['id'];
                    \think\Db::name('integral_group')->where('id',$id)->update($data);
                }else{
                    $data['username'] =  \think\Session::get('admin')['userid'];
                    $data['inputtime'] = time();
                    \think\Db::name("integral_group")->insert($data);
                }
               $this->success("添加成功");
               
              
            }else{
                $this->error("请添加分组");
            }
        }
        $info = \think\Db::name("integral_group")->where(array('starttime'=>$row['start_time'],'endtime'=>$row['end_time']))->find();
        $this->assign('info',$info);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    protected function thecks($val){
        if(is_array($val) && $val[0]!=''){
            return true;
        }
        return false;
    }
    /**
    *发布任务
    */
    public function user_task($ids = NULL){
         if ($ids) {
            $row = $this->model->get($ids);
         if (!$row)
            $this->error(__('No Results were found'));
            $info = GenerateWeekUserTask($ids,$row);
            if ($info) {
                $this->success();
            } else {
                $this->error(__('发布任务失败，请重试'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
	 /**
     * 添加
     */
    public function add(){
		
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
				//通过
				$params2  = GenerateWeek();
				//print_r($params2);die;
				if(empty($params2)) $this->error(__('You have no permission or data already exists'));
				//合并数据
				$params = array_merge($params,$params2);
				//print_R($params);die;
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
						//生成周默认成员
						model(GetTableModel('User'))->saveAll(GenerateWeekUser($this->model->id));
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
	
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 总公司财务填写
     */
    public function finance_books($ids = NULL)
    {
		
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
				
				$insert = [];
				$ed = 0;
				$ad = 0;
				foreach($params['price'] as $key=>$val){
					if($val['id']){
						$insert['edit'][$ed]['id'] =  $val['id'];
						$insert['edit'][$ed]['cost_id'] = $key; 
						$insert['edit'][$ed]['price'] = $val['price'];
						$insert['edit'][$ed]['z_publish'] = \think\Session::get('admin')['userid'];
					}else{
						$insert['add'][$ad]['extract_week'] = $ids;
						$insert['add'][$ad]['pay_type'] = 2;
						$insert['add'][$ad]['cost_id'] = $key;
						$insert['add'][$ad]['price'] = $val['price'];
						$insert['add'][$ad]['day'] = 1;
						$insert['add'][$ad]['publish'] = \think\Session::get('admin')['userid'];
						$insert['add'][$ad]['z_publish'] = \think\Session::get('admin')['userid'];
					}
					$ed++;
					$ad++;
				}
                try {
					if(isset($insert['add'])) model(GetTableModel('Books'))->saveAll($insert['add']);
					if(isset($insert['edit'])) model(GetTableModel('Books'))->saveAll($insert['edit']);
					if(isset($params['integral'])){
						$params['integral']['integral_subtraction'] = implode(',',$params['integral']['integral_subtraction']);
						$row->allowField(true)->save($params['integral']);
					}
					$this->success();
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
		$arr = TableListSqlQuery('AnalysisBooks2','books.`extract_week` = '.$ids.'');
		$WeekInfo['IntegralAccident'] = $this->model->getIntegralAccidentList();
		$WeekInfo['IntegralComplaint'] = $this->model->getIntegralComplaintList();
		$WeekInfo['IntegralSubtraction'] = $this->model->getIntegralSubtractionList();
        $this->view->assign("arr", $arr);
        $this->view->assign("row", $row);
        $this->view->assign("WeekInfo", $WeekInfo);
        return $this->view->fetch();
    }
	/**
     * 审核
     */
    public function status($ids = NULL){	
		
        if ($ids) {
            if ($this->request->isPost()) {
				$params = $this->request->post("row/a");
				if ($params) {
					try {
						$pk = $this->model->getPk();
						$list = $this->model->where($pk, 'in', $ids)->select();
						$count = 0;
						foreach ($list as $k => $v) {
							//$count += $v->delete();
							if($v->status == 2){
								$count += $v->allowField(true)->save($params);
							}
						}
						if ($count) {
							$this->success();
						} else {
							$this->error(__('没有需要审核的数据'));
						}
					} catch (\think\exception\PDOException $e) {
						$this->error($e->getMessage());
					}
				}
				$this->error(__('Parameter %s can not be empty', ''));
			}
			return $this->view->fetch();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 提交审核
     */
    public function check($ids = NULL){	
	
        if ($ids) {
            $pk = $this->model->getPk();
		
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
			$params['status'] = 2;
            foreach ($list as $k => $v) {
                //$count += $v->delete();
				if($v->status == 1 || $v->status == 4){
					$count += $v->allowField(true)->save($params);
				}
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

	 /**
     * 生成数据
     */
    public function generate(){
	   if ($this->request->isPost()) {
			$date = $this->request->post("date/a");
			if(empty($date)) $this->error(__('No Results were found'));
			$generate = GenerateWeekAll($date);
			if ($generate) {
                $this->success();
            } else {
                $this->error(__('No Results were found'));
            }
		}
        return $this->view->fetch();
    }
	/**
     *导出数据
     */
	public function excel(){
		//print_R(['2018-09-17,2018-09-23']);die;
		//$generate = ExcelWeekAll(['2018-09-17,2018-09-23','2018-09-24,2018-09-30']);
        if ($this->request->isPost()) {
			$date = $this->request->post("date/a");
			$type = $this->request->post("type");
			if(empty($date)) $this->error(__('No Results were found'));
					
			if($type == 1){
				$generate = ExcelWeekAll($date);
				if ($generate) {
					$title = date("YmdHis");
					$objWriter = PHPExcel_IOFactory::createWriter($generate, 'Excel2007');
					$excelName = "uploads/excel/周提成表-" . $title . ".xlsx";
					$objWriter->save($excelName);
					$this->success('',''.request()->domain().'/'.$excelName.'',$type);
				} else {
					$this->error(__('No Results were found'));
				}
			}elseif($type == 2){
				$generate = ExcelBooksWeekAll($date);
				//print_R($generate);die;
				if (!empty($generate)) {
					$this->success('','',$generate);
				} else {
					$this->error(__('No Results were found'));
				}
			}else{

				$this->error(__('No Results were found'));
			}
            
        }
		return $this->view->fetch();
    }
	
		 /**
     * 生成税金
     */
    public function generate_tax(){
	   if ($this->request->isPost()) {
			$submit = $this->request->post("submit");
			$year = $this->request->post("year");
			$month = $this->request->post("month");
			$date = $this->request->post("date/a");
			if((empty($date) && $submit == 1) || empty($submit)|| empty($year)|| empty($month)) $this->error(__('No Results were found'));
			$generate = ExcelWeektaxAll($submit,$date,$year.'-'.$month);
			if ($generate) {
				$title = date("YmdHis");
				$objWriter = PHPExcel_IOFactory::createWriter($generate, 'Excel2007');
				$excelName = "uploads/excel/月提成表-" . $title . ".xlsx";
				$objWriter->save($excelName);
                $this->success('',''.request()->domain().'/'.$excelName.'');
            } else {
                $this->error(__('No Results were found'));
            }
		}
        return $this->view->fetch();
    }
	/**
     * 删除
     */
    public function delete($ids = "")
    {
	
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
 	 /**
     * 详情
     * @param  int    $id  
     * @return array
	 * @author gzy
	 * @date   2018年8月30日 16:00:00
     */
    public function view($ids = NULL,$type = NULL,$day = NULL){
        $row = $this->model->get($ids);
  
		$active_fa = $this->request->get("active_fa",'Score');
		$active = $this->request->get("active",'Books');
		$this->view->assign("active_fa", $active_fa);
		$this->view->assign("active", $active);
        if (!$row) $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
		
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
		//print_r($row);die;
		$WeekModel = GetWeekModel($row);
		//print_R($this->view_data($ids,$WeekModel,null,$row));die;
        if(isset($WeekModel['Score']['Check'])) unset($WeekModel['Score']['Check']);
		$this->view->assign("WeekModel", $WeekModel);
        $this->view->assign("row", $row);
        $this->view->assign("id", $ids);

		if($type == 'Books_view'){
			$WeekModel = [$type=>[]];
			$this->view->assign($type,$this->view_data($ids,$WeekModel,$day,$row = []));
			return $this->view->fetch('books_view');
		}else{
			$this->view->assign("WeekInfo",$this->view_data($ids,$WeekModel,null,$row));
		}
        return $this->view->fetch();
    }
	 /**
     * 通用数据
     * @param  int    $id  
     * @param  arr    $WeekModel  所拥有权限模块
     * @return array
	 * @author gzy
	 * @date   2018年8月30日 16:30:00
     */
	public function view_data($id = NULL,$WeekModel = [],$day = NULL,$row = []){;
		if(empty($id) || empty($WeekModel)) return false;
		$WeekInfo = [];
		foreach($WeekModel as $key=>$val){
		//	if($key == 'Round_book') continue;
			foreach($val as $k=>$v){
                if($k == 'Check') continue;
				switch ($k) {
					 case 'Books_view':
						$WeekInfo[$k] = TableListSqlQuery($k,'`extract_week` = '.$id.' and `day` = '.$day.'');
			
						break;
					 case 'Books':
						$WeekInfo[$k] = [];
						$WeekInfo[$k] = TableListSqlQuery($k,'`extract_week` = '.$id.'');
						foreach($WeekInfo[$k] as $kk=>&$vv){
							$vv['Books_view'] = TableListSqlQuery($k.'_view','`extract_week` = '.$id.' and `day` = '.$vv['day'].'');
						}
						//print_r($WeekInfo[$k]);die;
						break;
					 case 'Analysis':
						 //print_R(GetAnalysisAll($k,$id));die;
						//$WeekInfo[$k] = !empty($row['analysis']) ? unserialize($row['analysis']):GetAnalysisAll($k,$id);
						$WeekInfo[$k] = GetAnalysisAll($k,$id);
						$WeekInfo[$k]['books'] = !empty($row['books']) ?  unserialize($row['books']) : GetAnalysisBooks($k,$id);
						//print_R($WeekInfo[$k]['books']);die;
						break;
					 case 'User':
						$WeekInfo[$k] =  TableListSqlQuery($k.'Extract',"u.extract_week = '".$id."'");
					
						if(!empty($WeekInfo[$k])){ 
                           // $WeekInfo[$k.'Extract'] = !empty($row['userextract']) ? unserialize($row['userextract']) : GetUserExtractAll($WeekInfo[$k],$id);
							$WeekInfo[$k.'Extract'] = GetUserExtractAll($WeekInfo[$k],$id);
							$WeekInfo[$k.'RoundExtract'] = !empty($row['userextract_round']) ? unserialize($row['userextract_round']) : GetUserRoundExtractAll($WeekInfo[$k],$id);
							//$WeekInfo[$k.'RoundExtract'] = GetUserRoundExtractAll($WeekInfo[$k],$id);
						}
						break;
					case 'Venue_sales':
						$WeekInfo[$k] = TableList('Season',$id,'extract_week');
						break;
					case 'Round_analysis':
						$WeekInfo[$k] = !empty($row['analysis_round']) ? unserialize($row['analysis_round']):GetRoundAnalysisAll($k,$id);
                        //$WeekInfo[$k] = GetRoundAnalysisAll($k,$id);
					    //print_R(GetRoundAnalysisAll($k,$id));die;
						break;
					default:
						$WeekInfo[$k] = TableList($k,$id,'extract_week');
						break;
				 }
			}
		}

		return $WeekInfo;
	}
	 /**
     * 通用添加
     * @param  int    $id  
     * @param  arr    $type  所拥有权限模块
     * @return array
	 * @author gzy
	 * @date   2018年8月30日 17:00:00
     */
	public function public_add($id = NULL, $type = Null){
		if(empty($id) || empty($type)) $this->error(__('Parameter %s can not be empty', $id ? 'id' : 'type'));
		$info = $this->model->get($id);
		//print_R(GetBaseInfo('Public')['BookPrice']);die;
        if (!$info) $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            
            if ($params) {
				if($type != 'Analysis'){
					$model = model(GetTableModel($type));
					$params['extract_week']    = $id;
					$params['publish']    = \think\Session::get('admin')['userid'];
					$params['z_publish']  = \think\Session::get('admin')['userid'];
				}else{
					 $result = $info->allowField(true)->save($params);
					 $this->success();
				}
				if($type == 'Season'){
				    $params['province'] = $this->request->post("province");
					$params['city'] = $this->request->post("city");
					$params['area'] = $this->request->post("area");
				}
				if($type == 'School'){
                    //添加追加退货
                    if($params['type'] == 2 || $params['type'] == 3){
                        $School = explode('-', $params['school_id']);
                        $params['school_id'] = $School[1];
                        $params['zschool_id'] = $School[0];
                    }
                }
				if($type == 'User'){
					$info = TableField('User','userid',$params['userid'],'userid',['extract_week'=>$id]);
					if(!empty($info)) $this->error('用户数据已存在');
					$data = $this->request->post("position/a");
					$params['position'] = implode(',',$data);
				}
				if($type == 'Books' && $params['pay_type'] == 2 && !$params['cost_id']){
					$this->error('请选择费用项目');
				}
                try {
                    $result = $model->allowField(true)->save($params);
                    if ($result !== false) {
						//添加学校信息
						if($type == 'School'){
							$data = $this->request->post("data/a");
							if(!empty($data)){
                                //判断追加退货
                               if($params['type'] == 2 || $params['type'] == 3){
                                    model(GetTableModel($type.'_data'))->saveAll(HandleSchool($model->id,$data,$School[0]));
                                }else{
                                    model(GetTableModel($type.'_data'))->saveAll(HandleSchool($model->id,$data));
                                }
								
							}
						}
                        $this->success();
                    } else {
                        $this->error($model->getError());
                    }

                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		if($type == 'Books'){
			$displayBooks = 1;
			if(!empty(TableList('Books',$id,'extract_week'))){
				$displayBooks = 2;
			}
			$this->view->assign("displayBooks",$displayBooks);
		}
		//print_R($info);die;
		$this->view->assign("id",$id);
		$this->view->assign("info",$info);
		$this->view->assign("username",\think\Session::get('admin')['username']);
		$this->view->assign("WeekInfo",$this->type_info($type,'','',$id));

        return $this->view->fetch('public_add_'.strtolower($type));
		
	}
     /**
     * 组合定价详情
     * @param  int    $id  
     * @return array
     * @author gzy
     * @date   2018年12月29日 10:00:00
     */
     public function sales_pricing($id = NULL){
        if(is_null($id)) $this->error(__('Parameter %s can not be empty', 'id' ));
        $WeekInfo['RoundInfo'] = GetBaseInfo('RoundInfo');
        if ($this->request->isPost()) {
             $data = $this->request->post("data/a");
             $data['id'] = $id;
             return $this->success('成功',null,$data);
        }
        $this->view->assign("WeekInfo",$WeekInfo);
        $this->view->assign("id",$id);
        return $this->view->fetch('public_edit_venue_pricing');
    }
	 /**
     * 通用编辑
     * @param  int    $id  
     * @param  arr    $type  所拥有权限模块
     * @return array
	 * @author gzy
	 * @date   2018年8月31日 10:00:00
     */
	public function public_edit($id = NULL, $type = Null,$fa = NULL){
		if(empty($id) || empty($type)) $this->error(__('Parameter %s can not be empty', $id ? 'id' : 'type'));
		if($type == 'Venue_sales'){
			$model = model(GetTableModel('Season'));
		}else{
			$model = model(GetTableModel($type));
		}
		$row = $model->get($id);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
				$params['z_publish']  = \think\Session::get('admin')['userid'];
				if($type == 'Season'){
				    $params['province'] = $this->request->post("province");
					$params['city'] = $this->request->post("city");
					$params['area'] = $this->request->post("area");
				}
				if($type == 'User'){
					//$info = TableField('User','userid',$params['userid'],'userid',['extract_week'=>$id]);
					//if(!empty($info)) $this->error('用户数据已存在');
					unset($params['userid']);
					$data = $this->request->post("position/a");
					if(!empty($data)){
						$params['position'] = implode(',',$data);
					}
				}
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
						//添加学校信息
						if($type == 'School'){
							$data = $this->request->post("data/a");
							if(!empty($data)){
								$result = model(GetTableModel($type.'_data'))->where('extract_school','=',$id)->delete();
								model(GetTableModel($type.'_data'))->saveAll(HandleSchool($id,$data));
							}
						}
						//添加一轮书信息
						if($type == 'Venue_sales'){
							$data = $this->request->post("data/a");
							if(!empty($data)){
								$result = model(GetTableModel($type))->where('season_id','=',$id)->delete();
								model(GetTableModel($type))->saveAll(HandleRound($id,$data));
							}
						}
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		//print_R($this->type_info($type,$id,$row,$row->extract_week));die;
		$this->view->assign("WeekInfo",$this->type_info($type,$id,$row,$row->extract_week));
		$this->view->assign("row", $row);

        if($type == 'School'){
            if($row->type == 2 || $row->type == 3){
              return $this->view->fetch('public_edit_'.strtolower($fa.$type).'_t');
            }
        }
        return $this->view->fetch('public_edit_'.strtolower($fa.$type));
	}
	/**
     * 通用添加/编辑 数据
     */
    public function type_info($type = NULL,$id = NULL,$row = [],$pid = NULL) {
      if(empty($type) || $type == 'Analysis') return false;
	  $WeekInfo = [];
	  if($type == 'Venue_sales'){
		 $model = model(GetTableModel('Season'));
	  }else{
		 $model = model(GetTableModel($type));
	  }
	  switch ($type) {
			 case 'Books':
				$WeekInfo['payTypeList'] = $model->getPayTypeList();
				$WeekInfo['statusList'] = $model->getStatusList();
				$WeekInfo['dayList'] = $model->getDaylist();
				$WeekInfo['Cost'] = TableList('Cost','1','delete_status',['type'=>1]);
				break;
			 case 'User':
				 $WeekInfo['statusList'] = $model->getStatusList();
                $position_data = array_column(collection(model(GetTableModel('AuthGroup'))::field('id,name')->whereIn('id',"'".GetBaseInfo('FPosition')."'")->order('weigh', 'desc')->select())->toArray(), 'name','id');
				//职位信息
				$WeekInfo['position_data'] = $position_data;
				if(isset($row->position)){
					$WeekInfo['position'] = explode(',',$row->position);
				}
                break;
			 case 'Season':
				 $WeekInfo['Subject_id'] = TableList('Subject');
				 $WeekInfo['regLevelList'] = $model->getRegLevelList();
                break;
			 case 'School':
				 if(!empty($pid)){
					$WeekInfo['User'] = array_column(TableList('User',$pid,'extract_week'),null,'userid');
				}
				if(!empty($id)){
					$SalesPrice = TableList('School_data','1','delete_status',['extract_school'=>$id,'type'=>2],'weigh','asc');
			        $WeekInfo['SalesPrice'] = array_column($SalesPrice, 'num','price');
					$UserInfo = array_column(TableList('School_data','1','delete_status',['extract_school'=>$id,'type'=>1],'weigh','asc'),'proportion','userid');
				    /*$Info = [];
					if(!empty($UserInfo)){
						foreach($UserInfo as $key=>$val){
							$Info[$key]['key'] = $val['userid'];
							$Info[$key]['value'] = $val['proportion'];
						}
					}*/
			        $WeekInfo['UserInfo'] = !empty($UserInfo) ? json_encode($UserInfo):'';
					$WeekInfo['UserNum'] = count($UserInfo);
			    }
				$WeekInfo['BookPrice'] = GetBaseInfo('Public')['BookPrice'];
				$WeekInfo['regLevelList'] = $model->getRegLevelList();
				$WeekInfo['rankingLevelList'] = $model->getRankingLevelList();
                $WeekInfo['LevelList'] = $model->getLevelList();
				$WeekInfo['TypeList'] = $model->getTypeList();
                break;
			 case 'Venue_sales':
				 if(!empty($pid)){
					$WeekInfo['RoundInfo'] = GetBaseInfo('RoundInfo');
				}
				if(!empty($id)){
					$SalesInfo = TableList('Venue_sales',$id,'season_id',[],'weigh','asc');
			        $WeekInfo['SalesInfo'] = !empty($SalesInfo) ? json_encode($SalesInfo):'';
					$WeekInfo['SalesNum'] = count($SalesInfo);
			    }
                break;
            default:
                break;
      }
	  return $WeekInfo;
    }
	 /**
     * 通用删除
     * @param  int    $id  
     * @param  arr    $type  所拥有权限模块
     * @return array
	 * @author gzy
	 * @date   2018年8月31日 11:00:00
     */
	public function public_delete($id = NULL, $type = Null){
		if(empty($id) || empty($type)) $this->error(__('Parameter %s can not be empty', $id ? 'id' : 'type'));
		$model = model(GetTableModel($type));
		$row = $model->get($id);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($id) {
            $pk = $model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $model->where($pk, 'in', $id)->select();
            $count = 0;
            foreach ($list as $k => $v) {
				
                $count += $v->delete();
			
            }
            if ($count) {
				//删除学校信息
				if($type == 'School'){
					$result = model(GetTableModel($type.'_data'))->where('extract_school','=',$id)->delete();
				}
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
	}
	/**
     *通用导出
     */
	public function public_export($id = NULL, $type = Null){
        $export = ExcelWeekSales($id,$type);
		return ;
    }

	
  
}
